package com.jing.system.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
 * File Util
 * @author jing.yue
 * @version 1.0
 * @since 2012-10-12
 *
 */
public class FileUtil {

	private static final Logger logger = Logger.getLogger(FileUtil.class);

	/**
	 * 创建指定路径的文件夹[不存在,则创建]
	 * @param destDirName
	 */
	public static void createDir(String destDirName) {
		File dir = new File(destDirName);
		if(dir.exists()) {
			logger.info("创建目录" + destDirName + "失败，目标目录已存在!");
		}
		else {
			if(!destDirName.endsWith(File.separator)) {
				destDirName = destDirName + File.separator;
			}
			//创建目录
			dir.mkdirs();
		}
	}

	/**
	 * 读取文件[不存在,则创建]
	 * @param destFileName 文件名
	 * @return 创建成功返回true,否则返回false
	 * @throws IOException
	 */
	public static File readFile(String destFileName) throws IOException {
		File file = new File(destFileName);
		if (file.exists()) {
			logger.info("目标文件已存在: " + destFileName);
			return file;
		}
		if (!file.getParentFile().exists()) {
			if (!file.getParentFile().mkdirs()) {
				logger.info("创建目录文件所在的目录失败!");
			}
		}
		//创建目标文件
		if (file.createNewFile()) {
			logger.info("创建单个文件成功: " + destFileName);
		} else {
			logger.info("创建单个文件失败: " + destFileName);
		}
		return file;
	}

	/**
	 * 读取文件为byte[]
	 * @param destFileName
	 * @return
	 */
	public static byte[] readFileBytes(String destFileName) {
		try {
			BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(destFileName));
			int len = bufferedInputStream.available();
			byte[] bytes = new byte[len];
			int r = bufferedInputStream.read(bytes);
			if (len != r) {
				bytes = null;
				throw new IOException("读取文件不正确");
			}
			bufferedInputStream.close();
			return bytes;
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
		}
		catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}
}
